﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using System.Data;
using EntitiesTM;
using System.Text;
using System.IO;

namespace TimeWork.report
{
    public partial class DetailedManager : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["email"] == null)
            {
                Response.Redirect("http://"+Request.Url.Authority+"/Login.aspx");
            }
            if (!IsPostBack)
            {
                ddlActivity.Visible = false;
                fillData();
            }
        }

        protected void ddlTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlMonth.Visible = false;
            lblStart.Visible = false;
            lblEnd.Visible = false;
            txtEndTime.Visible = false;
            txtStartTime.Visible = false;
            switch (Int32.Parse(ddlTime.SelectedValue))
            {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    ddlMonth.Visible = true;
                    break;
                case 6:
                    break;
                case 7:
                    lblStart.Visible = true;
                    lblEnd.Visible = true;
                    txtEndTime.Visible = true;
                    txtStartTime.Visible = true;
                    break;
            }
        }
        private void BindDdlProject()
        {
            Dictionary<string, string> data = BuProject.selProjectByParentIDTreeReport(0, Session["companyid"].ToString());
            ListItem item;
            item = new ListItem("Tất cả sản phẩm", "0");
            ddlproject.Items.Add(item);

            foreach (KeyValuePair<string, string> pair in data)
            {
                item = new ListItem(pair.Value, pair.Key);
                ddlproject.Items.Add(item);
            }
        }

        protected void ddlproject_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!ddlproject.SelectedValue.Equals("0"))
            {
                int projectLevel = BuProject.selProjectByIDTree(Int32.Parse(ddlproject.SelectedValue), Session["companyid"].ToString()).projectLevel;
                if (projectLevel == 3)
                {
                    // Cho hien DropDownList activity va do du lieu
                    ddlActivity.Visible = true;
                    EnProject project = new EnProject();
                    project.projectID = Int32.Parse(ddlproject.SelectedValue);
                    ddlActivity.DataSource = BuProject.selActivityByProjectExceptID(project, Session["companyid"].ToString());
                    ddlActivity.DataTextField = "ActivityName";
                    ddlActivity.DataValueField = "ActivityID";
                    ddlActivity.DataBind();
                    ddlActivity.Items.Insert(0, new ListItem("Tất cả công việc", "0"));
                    ddlActivity.SelectedValue = "0";
                }
                else
                {
                    ddlActivity.Visible = false;
                }
                string value = ddlActivity.SelectedValue;
            }
            else
            {
                ddlActivity.Visible = false;
            }
        }
        public void fillData()
        {
            BindDdlProject();

            ddlUser.DataSource = BuStaff.selAllStaffOptByResultUnit(Session["email"].ToString(), Session["companyid"].ToString());
            ddlUser.DataTextField = "StaffName";
            ddlUser.DataValueField = "StaffID";
            ddlUser.DataBind();
            ddlUser.Items.Insert(0, new ListItem("Tất cả người dùng", "0"));
            ddlUser.SelectedValue = "0";

            ddlClient.DataSource = BuClient.selAllClient(Session["companyid"].ToString());
            ddlClient.DataTextField = "ClientName";
            ddlClient.DataValueField = "ClientID";
            ddlClient.DataBind();
            ddlClient.Items.Insert(0, new ListItem("Tất cả đối tác", "0"));
            ddlClient.SelectedValue = "0";


            ddlResultUnit.DataSource = BuResultUnit.selAllResultUnit(Session["companyid"].ToString());
            ddlResultUnit.DataTextField = "ResultUnitName";
            ddlResultUnit.DataValueField = "ResultUnitID";
            ddlResultUnit.DataBind();
            ddlResultUnit.Items.Insert(0, new ListItem("Tất cả đơn vị", "0"));
            ddlResultUnit.SelectedValue = "0";

            ddlTypeTime.DataSource = BuProject.selAllTypeTime(Session["companyid"].ToString());
            ddlTypeTime.DataTextField = "TypeTimeName";
            ddlTypeTime.DataValueField = "TypeTimeID";
            ddlTypeTime.DataBind();
            ddlTypeTime.Items.Insert(0, new ListItem("Tất cả loại thời giờ", "0"));
            ddlTypeTime.SelectedValue = "0";
        }

        public void getParam()
        {
            try
            {
                string companyid = Session["companyid"].ToString();
                int project = Int32.Parse(ddlproject.SelectedValue);

                string time = ddlTime.SelectedValue;
                DateTime start = DateTime.Now;
                DateTime end = DateTime.Now;
                if (time.Equals("7"))
                {
                    start = DateTime.ParseExact(txtStartTime.Text, "d/M/yyyy", null);
                    end = DateTime.ParseExact(txtEndTime.Text, "d/M/yyyy", null);
                }

                int month = Int32.Parse(ddlMonth.SelectedValue);
                int user = Int32.Parse(ddlUser.SelectedValue);
                int client = Int32.Parse(ddlClient.SelectedValue);
                int resultUnit = Int32.Parse(ddlResultUnit.SelectedValue);
                int typeTime = Int32.Parse(ddlTypeTime.SelectedValue);
                bool enableClient = cbClient.Checked;
                DateTime date = DateTime.Now;
                string sql = String.Empty;
                if (enableClient)
                {
                    sql += "SELECT SAID 'ID', SADate 'Ngày', StaffName 'Họ tên', ClientName 'Đối tác', ProjectName 'Tên sản phẩm', ActivityName 'Tên công việc', SUM(SAReportTimeHour) 'Số giờ', SUM(SAReportTimeMinute) 'Số phút' , TypeTimeName 'Loại thời giờ', CAST(SADetails AS NVARCHAR(500)) 'Ghi chú'" +
                            " FROM VTK_SA" + companyid + " INNER JOIN VTK_Activity" + companyid + " ON SAActivityID = ActivityID INNER JOIN VTK_Project" + companyid + " ON ActivityProjectID = ProjectID INNER JOIN VTK_Staff" + companyid + " ON SAStaffID = StaffID INNER JOIN VTK_TypeTime" + companyid + " ON SATypeTimeID = TypeTimeID LEFT JOIN VTK_Client" + companyid + " ON ProjectClientID = ClientID ";
                }
                else
                {
                    sql += "SELECT SAID 'ID', SADate 'Ngày', StaffName 'Họ tên', ProjectName 'Tên sản phẩm', ActivityName 'Tên công việc', SUM(SAReportTimeHour) 'Số giờ', SUM(SAReportTimeMinute) 'Số phút' , TypeTimeName 'Loại thời giờ', CAST(SADetails AS NVARCHAR(500)) 'Ghi chú'" +
                           " FROM VTK_SA" + companyid + " INNER JOIN VTK_Activity" + companyid + " ON SAActivityID = ActivityID INNER JOIN VTK_Project" + companyid + " ON ActivityProjectID = ProjectID INNER JOIN VTK_Staff" + companyid + " ON SAStaffID = StaffID INNER JOIN VTK_TypeTime" + companyid + " ON SATypeTimeID = TypeTimeID LEFT JOIN VTK_Client" + companyid + " ON ProjectClientID = ClientID ";
                }
                if (time.Equals("1"))
                {
                    sql += "WHERE CONVERT(varchar(10),SADate,101) = CONVERT(varchar(10),CAST('" + date + "' AS DATETIME), 101) ";
                }
                if (time.Equals("2"))
                {
                    sql += "WHERE CONVERT(varchar(10),SADate,101) = CONVERT(varchar(10),CAST(DATEADD(DD,-1,'" + date + "') AS DATETIME), 101) ";
                }
                if (time.Equals("3"))
                {
                    sql += "WHERE DATEPART(MM,'" + date + "') = DATEPART(MM,SADate) ";
                }
                if (time.Equals("4"))
                {
                    sql += "WHERE DATEPART(MM,'" + date + "')-1 = DATEPART(MM,SADate) ";
                }
                if (time.Equals("5"))
                {
                    sql += "WHERE DATEPART(MM,SADate) = " + month + " ";
                }
                if (time.Equals("6"))
                {
                    sql += "WHERE 1 = 1 ";
                }
                if (time.Equals("7"))
                {
                    sql += "WHERE CONVERT(varchar(10),SADate,101) >= CONVERT(varchar(10),CAST('" + start + "' AS DATETIME), 101) AND CONVERT(varchar(10),SADate,101) <= CONVERT(varchar(10),CAST('" + end + "' AS DATETIME), 101) ";
                }

                if (project != 0)
                {
                    // Neu project != 0 thi phai them dieu kien
                    int projectLevel = BuProject.selProjectByIDTree(Int32.Parse(ddlproject.SelectedValue), Session["companyid"].ToString()).projectLevel;
                    // Truong hop level = 3 thi xuat hien lua chon cong viec
                    if (projectLevel == 3)
                    {
                        // Truong hop chon tat ca
                        if (ddlActivity.SelectedValue.Equals("0"))
                        {
                            sql += "AND ProjectID = " + project + " ";
                        }
                        // Neu chi chon lua 01 activity
                        else
                        {
                            sql += "AND SAActivityID = " + ddlActivity.SelectedValue + " ";
                        }
                    }
                    if (projectLevel == 2)
                    {
                        sql += "AND ProjectID IN (SELECT ProjectID FROM VTK_Project" + companyid + " WHERE ProjectParentID =  " + project + ") ";
                    }
                    if (projectLevel == 1)
                    {
                        sql += "AND ProjectID IN (SELECT ProjectID FROM VTK_Project" + companyid + " WHERE ProjectParentID IN (SELECT ProjectID FROM VTK_Project" + companyid + " WHERE ProjectParentID =  " + project + ")) ";
                    }

                }
                

                if (client != 0)
                {
                    sql += "AND ClientID = " + client + " ";
                }

                int resultUnitID = BuStaff.selResultUnitIDByEmail(Session["email"].ToString(), Session["companyid"].ToString());
                // Truong hop khong ton tai resultUnit
                if (resultUnitID == 0)
                {
                    // Chi show bao cao ca nhan
                    int staffID = BuStaff.selStaffIDByEmail(Session["email"].ToString(), Session["companyid"].ToString());
                    sql += "AND SAStaffID = " + staffID + " ";                   
                }
                else
                {
                    if (user != 0)
                    {
                        sql += "AND SAStaffID = " + user + " ";
                    }
                    else
                    {
                        sql += "AND StaffResultUnitID = " + resultUnitID + " ";
                    }

                }

                if (typeTime != 0)
                {
                    sql += "AND TypeTimeID = " + typeTime + " ";
                }
                sql += "AND (SAReportTimeHour!=0 OR SAReportTimeMinute!=0) ";
                if (enableClient)
                {
                    sql += "GROUP BY SAID, SADate, StaffName, ClientName, ProjectName, ActivityName, TypeTimeName, CAST(SADetails AS NVARCHAR(500)) ORDER BY SADate";
                }
                else
                {
                    sql += "GROUP BY SAID, SADate, StaffName, ProjectName, ActivityName, TypeTimeName, CAST(SADetails AS NVARCHAR(500)) ORDER BY SADate";
                }
                gvReport.Visible = false;
                gvReportClient.Visible = false;
                lblData.Text = String.Empty;
                DataTable data = BuReport.selReportDetailedOri(sql);

                if (data.Rows.Count > 0)
                {
                    if (enableClient)
                    {
                        gvReportClient.Visible = true;
                        gvReportClient.DataSource = BuReport.selReportDetailedOri(sql);
                        gvReportClient.DataBind();
                    }
                    else
                    {
                        gvReport.Visible = true;
                        gvReport.DataSource = BuReport.selReportDetailedOri(sql);
                        gvReport.DataBind();
                    }
                }
                else
                {
                    lblData.Text = "Chưa có dữ liệu";
                }
            }
            catch { }
        }

        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            getParam();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }
        protected void btnExportExcel_Click(object sender, ImageClickEventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AppendHeader("Content-Disposition", "attachment;filename=BaoCaoChiTiet" + DateTime.
            Now.ToString("yyyyMMdd") + ".xls");
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-excel";
            this.EnableViewState = false;

            var sb = new StringBuilder();
            getParam();gvReport.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
            Response.Write(sb.ToString());
            Response.End();
        }

        private int totalHour = 0;
        private int totalMinute = 0;
        protected void gvReport_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label txtTimeReport = (Label)e.Row.FindControl("lblDate");
                DateTime tmp = DateTime.Parse(txtTimeReport.Text);
                txtTimeReport.Text = tmp.ToString("dd/MM/yyyy");

                totalHour += Int32.Parse(((Label)e.Row.FindControl("lblHour")).Text);
                totalMinute += Int32.Parse(((Label)e.Row.FindControl("lblMinute")).Text);
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (totalMinute >= 60)
                {
                    int addHour = totalMinute / 60;
                    totalMinute -= 60 * addHour;
                    totalHour += addHour;
                }
                Label lblSumHour = (Label)e.Row.FindControl("lblSumHour");
                lblSumHour.Text = totalHour.ToString() + "h";

                Label lblSumMinute = (Label)e.Row.FindControl("lblSumMinute");
                lblSumMinute.Text = totalMinute.ToString() + "m";

            }
        }

        protected void gvReportClient_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label txtTimeReport = (Label)e.Row.FindControl("lblDate");
                DateTime tmp = DateTime.Parse(txtTimeReport.Text);
                txtTimeReport.Text = tmp.ToString("dd/MM/yyyy");

                totalHour += Int32.Parse(((Label)e.Row.FindControl("lblHour")).Text);
                totalMinute += Int32.Parse(((Label)e.Row.FindControl("lblMinute")).Text);
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                if (totalMinute >= 60)
                {
                    int addHour = totalMinute / 60;
                    totalMinute -= 60 * addHour;
                    totalHour += addHour;
                }
                Label lblSumHour = (Label)e.Row.FindControl("lblSumHour");
                lblSumHour.Text = totalHour.ToString() + "h";

                Label lblSumMinute = (Label)e.Row.FindControl("lblSumMinute");
                lblSumMinute.Text = totalMinute.ToString() + "m";
            }
        }

        

    }
}